/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package presentacion.utilidad.event_queue;

import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
import javax.swing.MenuSelectionManager;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

/**
 * Suggested serving size:
 * Toolkit.getDefaultToolkit().getSystemEventQueue().push(new WaitCursorEventQueue(70));
 */
public class MyEventQueue extends EventQueue
    implements DelayTimerCallback {
  private final CursorManager cursorManager;
  private final DelayTimer waitTimer;

  public MyEventQueue(int delay) {
    this.waitTimer = new DelayTimer(this, delay);
    this.cursorManager = new CursorManager(waitTimer);
  }
  public void close() {
    waitTimer.quit();
    pop();
  }
  protected void dispatchEvent(AWTEvent event) {
    cursorManager.push(event.getSource());
    waitTimer.startTimer();
    try {
      super.dispatchEvent(event);
      clickDerecho(event);
    } finally {
      waitTimer.stopTimer();
      cursorManager.pop();
    }
  }
  public AWTEvent getNextEvent() throws InterruptedException {
    waitTimer.stopTimer(); //started by pop(), this catches modal dialogs 
    //closing that do work afterwards
    return super.getNextEvent();
  }
  public void trigger() {
    cursorManager.setCursor();
  }
  
  public void clickDerecho(AWTEvent event) {
      // interested only in mouseevents
      if(!(event instanceof MouseEvent))
          return;

      MouseEvent me = (MouseEvent)event;

      // interested only in popuptriggers
      if(!me.isPopupTrigger())
          return;

      // me.getComponent(...) retunrs the heavy weight component on which event occured
      Component comp = SwingUtilities.getDeepestComponentAt(
              me.getComponent(), me.getX(), me.getY());

      // interested only in textcomponents
      if(!(comp instanceof JTextComponent))
          return;

      // no popup shown by user code
      if(MenuSelectionManager.defaultManager().getSelectedPath().length > 0)
          return;

      // create popup menu and show
      JTextComponent tc = (JTextComponent)comp;
      JPopupMenu menu = new JPopupMenu();
      menu.add(new CutAction(tc));
      menu.add(new CopyAction(tc));
      menu.add(new PasteAction(tc));
      menu.add(new DeleteAction(tc));
      menu.addSeparator();
      menu.add(new SelectAllAction(tc));

      Point pt = SwingUtilities.convertPoint(
      me.getComponent(), me.getPoint(), tc);
      menu.show(tc, pt.x, pt.y);
  }  
  
}